﻿using Abp.Domain.Repositories;
using Abp.EntityFramework;
using Abp.ObjectMapping;
using Abp.UI;
using AVIS.OutBound.AWD;
using AVIS.OutBound.CarGroups;
using AVIS.OutBound.EntityFramework.Models;
using AVIS.OutBound.Orders;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace AVIS.OutBound.EntityFramework.Repositories
{
    public class OrderRepository : OutBoundRepositoryBase<avisOBOrder>, IOrderRepository
    {
        private readonly IRepository<avisOBOrderExt> _orderExtRepository;
        private readonly IRepository<avisOBOrder> _orderRepository;
        private readonly IAWDManager _awdManager;
        private readonly IObjectMapper _objectMapper;

        public OrderRepository(IDbContextProvider<OutBoundDbContext> dbContextProvider,
            IRepository<avisOBOrderExt> orderExtRepository,
            IRepository<avisOBOrder> orderRepository,
            IObjectMapper objectMapper,
            IAWDManager awdManager)
            : base(dbContextProvider)
        {
            _orderExtRepository = orderExtRepository;
            _objectMapper = objectMapper;
            _orderRepository = orderRepository;
            _awdManager = awdManager;
        }

        /// <summary>
        /// 获取指定的订单号数据
        /// </summary>
        /// <param name="orderNo">订单号</param>
        /// <param name="surname">用户的姓</param>
        /// <returns></returns>
        public Order GetOrder(string orderNo, string surname = "")
        {
            Expression<Func<avisOBOrder, bool>> filter = c => c.ReservationNumber == orderNo;
            if (!string.IsNullOrEmpty(surname))
            {
                filter = c => c.ReservationNumber == orderNo && c.Surname == surname;
            }

            var AvisOrder = _orderRepository.FirstOrDefault(filter);
            var AvisOrderExt = _orderExtRepository.FirstOrDefault(c => c.ReservationNumber == orderNo);
            return MapToOrder(AvisOrder, AvisOrderExt);
        }

        /// <summary>
        /// 保存订单到数据库
        /// </summary>
        /// <param name="order">订单</param>
        public void SaveOrder(Order order)
        {
            // 保存订单信息
            var avisOrder = _orderRepository.FirstOrDefault(a => a.ReservationNumber == order.OrderNo && a.Surname == order.Surname);
            if (avisOrder == null)
            {
                var ao = ToAvisOBOrder(order);
                _orderRepository.Insert(ao);
            }
            else
            {
                ToAvisOBOrder(order, avisOrder);
                _orderRepository.Update(avisOrder);
            }

            // 保存订单扩展信息
            var avisOrderExt = _orderExtRepository.FirstOrDefault(a => a.ReservationNumber == order.OrderNo);
            if (avisOrderExt == null)
            {
                //新建一条数据
                avisOrderExt = new avisOBOrderExt();
                avisOrderExt.OrderGuid = order.OrderId;
                avisOrderExt.ReservationNumber = order.OrderNo;
                avisOrderExt.CarGroupJson = JsonConvert.SerializeObject(order.CarGroup);
                _orderExtRepository.Insert(avisOrderExt);
            }
            else
            {
                avisOrderExt.CarGroupJson = JsonConvert.SerializeObject(order.CarGroup);
                _orderExtRepository.Update(avisOrderExt);
            }
        }

        /// <summary>
        /// 取消定单(逻辑删除)
        /// </summary>
        /// <param name="order">订单</param>
        public void CancelOrder(Order order)
        {
            if (order == null
                || string.IsNullOrWhiteSpace(order.OrderNo)
                || string.IsNullOrWhiteSpace(order.Surname))
            {
                throw new UserFriendlyException("对不起，订单信息有误，订单号和姓不能为空");
            }

            var data = _orderRepository.FirstOrDefault(a => a.ReservationNumber == order.OrderNo && a.Surname == order.Surname);
            if (data != null)
            {
                data.IsCancel = order.IsCancel;
                data.CancelReason = order.CancelReason;
                data.ModifyDate = Abp.Timing.Clock.Now;
                data.ModifyUser = "avis";
                _orderRepository.Update(data);
            }
        }

        /// <summary>
        /// 更新订单的YouyouOrderID
        /// </summary>
        /// <param name="orderNo">订单号</param>
        /// <param name="youyouOrderID"></param>
        public void UpdateYouyouOrderID(string orderNo, int youyouOrderID)
        {
            var data = _orderRepository.FirstOrDefault(a => a.ReservationNumber == orderNo);
            if (data != null)
            {
                data.YouyouOrderID = youyouOrderID;
                _orderRepository.Update(data);
            }
        }

        #region 私有方法
        /// <summary>
        /// 将订单转为AVIS订单对象
        /// </summary>
        /// <param name="realAWD">AWD</param>
        /// <param name="Order">订单</param>
        /// <param name="obOrder">AVIS订单</param>
        /// <returns></returns>
        private avisOBOrder ToAvisOBOrder(Order Order, avisOBOrder obOrder = null)
        {
            if (obOrder == null)
            {
                obOrder = new avisOBOrder();
                obOrder = _objectMapper.Map<avisOBOrder>(Order);
                obOrder.Postcode = obOrder.Postcode == null ? "" : obOrder.Postcode;
                obOrder.IsSendMessage = obOrder.IsSendMessage.HasValue ? obOrder.IsSendMessage : false;
                obOrder.DiscountCost = obOrder.DiscountCost.HasValue ? obOrder.DiscountCost : 0;
                obOrder.IsNoFlightNumber = obOrder.IsNoFlightNumber.HasValue ? obOrder.IsNoFlightNumber : false;

                obOrder.CardNum = "";
                obOrder.AmountCNY = 0;
                obOrder.Remark = "";
                obOrder.YouyouOrderID = 0;
                obOrder.IsEmail = false;
                obOrder.CreateDate = Abp.Timing.Clock.Now;
                obOrder.CreateUser = "avis";
                obOrder.ModifyDate = Abp.Timing.Clock.Now;
                obOrder.ModifyUser = "avis";

            }
            else
            {
                obOrder = _objectMapper.Map<avisOBOrder>(Order);
                obOrder.CardNum = "";
                obOrder.AmountCNY = 0;
                obOrder.Remark = "";
                obOrder.YouyouOrderID = 0;
                obOrder.IsEmail = false;
                obOrder.ModifyDate = Abp.Timing.Clock.Now;
                obOrder.ModifyUser = "avis";
            }

            return obOrder;
        }

        /// <summary>
        /// 将AVIS订单对象转为Order对象
        /// </summary>
        /// <param name="AvisOrder"></param>
        /// <param name="AvisOrderExt"></param>
        /// <returns></returns>
        private Order MapToOrder(avisOBOrder AvisOrder, avisOBOrderExt AvisOrderExt)
        {
            if (AvisOrder != null)
            {
                var data = _objectMapper.Map<Order>(AvisOrder);
                data.OrderStep = 7;
                data.RentalUnit = "天";

                if (AvisOrderExt != null)
                {
                    data.OrderId = AvisOrderExt.OrderGuid;
                    data.CarGroup = JsonConvert.DeserializeObject<CarGroup>(AvisOrderExt.CarGroupJson);
                }

                return data;
            }

            return null;
        }
        #endregion
    }
}
